<script setup>
import { ref, reactive, watch, h } from 'vue';
import { $t } from '@/locales';
import { fetchGetLogisticsChannel, fetchSetStorage, fetchSaveLogsChannel } from '@/service/api';
import { ElMessage, ElMessageBox } from 'element-plus'

defineOptions({ name: 'BindStoreModal' });
const props = defineProps(['rowData', 'warehouseData']);
const visible = defineModel('visible', { default: false });
const isLoading = ref(false);
const freight = ref([]);
const emit = defineEmits(['update:rowData']);
const model = ref(createDefaultModel());
function createDefaultModel() {
  return {
    ShopId: undefined,
    StorageId: undefined,
    freight: [],
    address: {
      name: '',
      phone: '',
      full_address: '',
    }
  };
}

function handleInitModel(){
  model.value = createDefaultModel()

  if(props.rowData){
    Object.assign(model.value, props.rowData)
  }
}

function getWarehourseOptions() {
  const warehouse = props.warehouseData.find(item => item.Id === model.value.StorageId)
  if(warehouse?.AddAddressJson){
    model.value.address = JSON.parse(warehouse.AddAddressJson)
  }
}

async function getLogisticsChannelOptions() {
  const { error, data }  = await fetchGetLogisticsChannel({ shopid: model.value.ShopId, storeageId: model.value.StorageId });
  if (!error) {
    freight.value = data.Data
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel()
    getWarehourseOptions()
    getLogisticsChannelOptions()
  }
});

function onChangeStorage(id){
  ElMessageBox({
    title: $t('common.warning'),
    type: 'warning',
    showCancelButton: true,
    message: h("div", { style: "font-size: 13px" },[
      h("p", null, $t("page.warehouse.confirm.biddTipLine_1")),
      h("p", null, $t("page.warehouse.confirm.biddTipLine_2")),
    ]),
    beforeClose: (action, instance, done) => {
      if(action === 'confirm'){
        instance.confirmButtonLoading = true

        const warehouse = props.warehouseData.find(item => item.Id === id)
        model.value.StorageId = id
        model.value.StorageName = warehouse.Name
        getWarehourseOptions()
        getLogisticsChannelOptions()
        done()
        instance.confirmButtonLoading = false
      }else{
        done()
      }
    }
  })
}

function handleCancel(){
  visible.value = false
}

function handleSave(){
  if(isLoading.value) return
  isLoading.value = true

  fetchSetStorage({
    Id: model.value.Id, 
    StorageId: model.value.StorageId,
    logistics: freight.value
  }).then(res => {
    window.$message?.success(res.data.Message)

    if(model.value.ShopType===0){
      fetchSaveLogsChannel({
        ShopID: model.value.ShopId,
        Logistics: freight.value
      })
    }
    // 触发更新事件
    emit('update:rowData', model.value)

    isLoading.value = false
    handleCancel()
  })
}
</script>

<template>
  <ElDialog v-model="visible" :title="$t('page.store.bindWarehouse')" class="w-1200px">
    <div class="w-624px mx-auto">
      <ElForm label-position="right" label-width="145px">
        <ElFormItem :label="$t('page.store.bindWarehouse')" prop="StorageId">
          <ElRadioGroup :model-value="model.StorageId" @change="onChangeStorage">
              <ElRadio
                v-for="item in props.warehouseData"
                :key="item.Id"
                :value="item.Id"
                :label="item.Name"
              />
            </ElRadioGroup>
        </ElFormItem>
        <div class="section-title mb-16px">退货地址：</div>
          <ElRow>
            <ElCol :span="12">
              <ElFormItem label="Name">{{ model.address.name }}</ElFormItem>
            </ElCol>
            <ElCol :span="12">
              <ElFormItem label="Phone">{{ model.address.phone }}</ElFormItem>
            </ElCol>
            <ElCol :span="24">
              <ElFormItem label="Address">{{ model.address.full_address }}</ElFormItem>
            </ElCol>
          </ElRow>
        <div class="section-title mb-16px">发货物流渠道：</div>
        <ElRow>
          <ElCol v-for="(item, index) of freight" :key="index" :span="12">
            <ElFormItem :label="item.LogisticName">
              <ElSwitch v-model="item.Enabled" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElForm>

      <div class="flex-x-center mt-18px">
        <el-space :size="16">
          <ElButton @click="handleCancel">{{ $t('common.cancel') }}</ElButton>
          <ElButton type="primary" :loading="isLoading" @click="handleSave">{{ $t('common.save') }}</ElButton>
        </el-space>
      </div>
    </div>
  </ElDialog>
</template>
